package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        /**
         * 根据toUserId查询 recommend_user , 根据score 排序，找第一条
         */
        Criteria criteria = Criteria.where("toUserId").is(toUserId);

        Query query = new Query(criteria).
                with(Sort.by(Sort.Order.desc("score")))
                .limit(1);

        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    /**
     * 分页查询推荐用户列表
     */
    public PageResult queryRecommendUserList(int page, int size, Long toUserId) {

        //1、创建Query对象
        Query query = new Query(Criteria.where("toUserId").is(toUserId))
                .limit(size).skip((page-1) * size).with(Sort.by(Sort.Order.desc("score")));

        //2、调用mongoTemplate查询总记录数
        long couns = mongoTemplate.count(query,RecommendUser.class );
        //3、调用mongoTemplate查询分页数据列表
        List<RecommendUser> list = mongoTemplate.find(query,RecommendUser.class);
        //4、返回值
        return new PageResult(page, size, (int)couns,list);
    }


    /**
     * 根据用户，查询推荐用户的缘分值
     */
    public Long queryScore(Long toUserId, Long userId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
                .and("toUserId").is(toUserId)
        );
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);

        if(user == null) {
            return 60l;
        }else{
            return user.getScore().longValue();
        }
    }
}
